<template>
    <a-control-group>
        <a-input-check-box-single :color="formItemHook.myColor" :size="formItemHook.mySize" :sharp="formItemHook.mySharp" :disabled="formItemHook.myDisabled || props.getDisabledFunc(a)" :plain="props.plain" v-for="a in props.items" :key="props.getTextFunc(a)" @click="methods.toggleItem(a)" :value="methods.isItemSelected(a)">
            <template v-slot:append>
                {{ props.getTextFunc(a) }}
            </template>
        </a-input-check-box-single>
    </a-control-group>
</template>

<script setup lang="ts">
import { InputPropsType, Rule_maxLength, Rule_minLength } from '@/types'
import AControlGroup from './AControlGroup.vue'
import AInputCheckBoxSingle from './AInputCheckBoxSingle.vue'
import { useFormItem } from '@/hooks/useFormItem'
import { useInput } from '@/hooks/useInput'

interface PropsType extends InputPropsType<any[], Rule_minLength | Rule_maxLength> {
    plain?: boolean
    items?: any[]
    getTextFunc: (a: any) => string
    getValueFunc: (a: any) => any
    getDisabledFunc: (a: any) => boolean
}
const props = withDefaults(defineProps<PropsType>(), {
    value: undefined,
    color: undefined,
    disabled: undefined,
    size: undefined,
    sharp: undefined,
    rules: () => [],
    isInner: false,
    plain: false,
    items: () => [],
    getTextFunc: (a: any) => a.text,
    getValueFunc: (a: any) => a.value,
    getDisabledFunc: (a: any) => a.disabled,
})

const emit = defineEmits<{
    (e: 'update:value', value: any[]): void
}>()
useInput(props)
const formItemHook = useFormItem(props)

const methods = {
    input(val: any[]) {
        emit('update:value', val)
    },
    toggleItem(item: any) {
        let itemValue = props.getValueFunc(item)
        if (methods.isItemSelected(item)) {
            methods.input(props.value.filter(a => a !== itemValue))
        } else {
            methods.input([...props.value, itemValue])
        }
    },
    isItemSelected(item: any) {
        let itemValue = props.getValueFunc(item)
        return props.value.some(a => a === itemValue)
    },
}
</script>